package com.example.tagsdemo.service.impl;

import com.example.tagsdemo.dao.StudentDao;
import com.example.tagsdemo.entity.Student;
import com.example.tagsdemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service(value = "studentService")
@Transactional
public class StudentServiceIpml implements StudentService {

    @Autowired
    private StudentDao studentDao;

    /**
     * 分页查询所有，带排序功能
     */
    @Override
    public List<Student> findAll() {
        // 创建查询条件数据对象
        Student  student = new Student();
        student.setName("王");

        // 创建匹配器，即规定如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());

        // 创建实例
        Example<Student> example = Example.of(student, matcher);
        // 查询
        List<Student> studentList = studentDao.findAll(example);

        //输出结果
        System.out.println("数量：" + studentList.size());
        for (Student s : studentList) {
            System.out.println(s.getName());
        }
        return studentList;
    }

    @Override
    public List<Student> list() {
        return studentDao.findAll();
    }


    @Override
    public Page<Student> findByName(String name, Integer pageNumber, Integer pageSize) {
        pageNumber = pageNumber == null || pageNumber < 0 ? 0: pageNumber - 1;
        ///Sort.Direction是个枚举有ASC(升序)和DESC(降序)
        Sort.Direction sort =  Sort.Direction.ASC;
        ///PageRequest继承于AbstractPageRequest并且实现了Pageable
        ///获取PageRequest对象 index:页码 从0开始  size每页容量 sort排序方式 "id"->properties 以谁为准排序
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort, "id");
        // 创建查询条件数据对象
        Student student = new Student();
        student.setName(name);
        // 创建匹配器，即规定如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());

        // 创建实例
        Example<Student> example = Example.of(student, matcher);

        Page<Student> page = studentDao.findAll(example,pageable);
        return page;
    }


}
